<template>
  <div>
    <!-- <button @click="showExportModel">daoshu</button> -->
    <el-row>
      <el-col :span="24">
        <div class="box">
          <div>
            <div class="box-header">
              <h3 class="box-title" style="line-height: 40px;float: left;">
                专家信息
              </h3>
              <el-upload
                style="display: inline; margin-left: 10px;margin-right: 10px;"
                action="#"
                ref="fileupload"
                accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                :show-file-list="false"
                :http-request="upLoadChange"
                :before-upload="beforeUpload"
              >
                <el-button size="small" type="primary"
                  >上传文件<i class="el-icon-upload2 el-icon--right"></i
                ></el-button>
              </el-upload>
              <el-button size="small" type="primary" @click="showExportModel()">
                <i class="el-icon-download el-icon--right">
                  下载模板
                </i>
              </el-button>
              <el-button
                size="small"
                type="success"
                @click="comfirmUpload()"
                v-if="tableData.length > 0"
              >
                <i class="el-icon-s-promotion el-icon--right">
                  确认上传
                </i>
              </el-button>
              <el-button
                v-if="showError"
                size="small"
                type="info"
                icon="el-icon-error el-icon--right"
                @click="exportError"
                >导出失败信息</el-button
              >
              <el-button
                round
                style="background: azure;float:right; margin-right: 50px;"
                @click="goback()"
                >返 回</el-button
              >
            </div>
            <div class="box-body">
              <!-- @cell-click="editCell" -->
              <!-- :cell-class-name="addClass" -->
              <!-- :cell-style="addClass" -->
              <el-table
                v-if="tableData.length > 0"
                :data="tableData"
                ref="multipleTable"
                border
                max-height="200"
                :cell-style="addClass"
              >
                <el-table-column
                  type="index"
                  label="#"
                  width="50"
                ></el-table-column>
                <el-table-column prop="name" label="专家姓名"></el-table-column>
                <el-table-column
                  prop="idnumber"
                  label="身份证号"
                ></el-table-column>
                <el-table-column
                  prop="direction"
                  label="研究方向"
                ></el-table-column>
                <el-table-column prop="jobrank" label="职称"></el-table-column>
                <el-table-column prop="unit" label="所在单位"></el-table-column>
                <el-table-column
                  v-if="showError"
                  prop="error"
                  label="失败原因"
                  width="200"
                ></el-table-column>
                <el-table-column label="操作" width="50">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="danger"
                      icon="el-icon-delete"
                      @click.stop="Delete(scope)"
                      circle
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="box-body" style="border-top: 1px dashed #d2d6de;">
              <h3 class="box-title" style="line-height: 40px;">
                当前项目已有专家
              </h3>
              <el-button
                size="small"
                type="success"
                style="margin-left: 6px;"
                @click="downExpert()"
                v-if="multipleSelection.length > 0"
              >
                <i class="el-icon-download el-icon--right">
                  下载专家
                </i>
              </el-button>
              <el-table
                :data="detailData"
                v-loading="loading"
                stripe
                @selection-change="handleSelectionChange"
              >
                <el-table-column
                  type="selection"
                  :context="_self"
                  width="50"
                ></el-table-column>
                <el-table-column
                  prop="id"
                  label="ID"
                  width="50"
                ></el-table-column>
                <el-table-column prop="name" label="专家姓名"></el-table-column>
                <el-table-column
                  prop="idnumber"
                  label="身份证号"
                  show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                  prop="direction"
                  label="研究方向"
                  show-overflow-tooltip
                ></el-table-column>
                <el-table-column prop="jobrank" label="职称" show-overflow-tooltip></el-table-column>
                <el-table-column prop="unit" label="所在单位" show-overflow-tooltip></el-table-column>
                <el-table-column
                  prop="username"
                  label="临时登陆账号"
                ></el-table-column>
                <el-table-column
                  prop="password"
                  label="临时登陆密码"
                ></el-table-column>
              </el-table>
              <el-pagination
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :pager-count="11"
                layout="prev, pager, next"
                :page-count="total"
                style="float: right;"
              ></el-pagination>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import http from './../../../../assets/js/http'
import XLSX from 'xlsx'
export default {
  data() {
    return {
      showError: false,
      multipleSelection: [],
      currentPage: 1,
      total: 1,
      prop: {
        name: '专家姓名',
        idnumber: '身份证号',
        direction: '研究方向',
        jobrank: '职称',
        unit: '所在单位'
      },
      tableData: [],
      detailData: [],
      loading: true
    }
  },
  methods: {
    goback() {
      router.go(-1)
    },
    // 导出模板
    showExportModel() {
      this.apiPost('admin/Download/DownloadExpert').then(res => {
        this.handelResponse(res, data => {
          window.location.href = res.data.file_dir
        })
      })
    },
    upLoadChange(content) {
      this.$message.success('文件解析成功，数据如下表')
    },
    // 解析文件为json格式
    beforeUpload(file) {
      this.tableData = []
      var reader = new FileReader()
      var _this = this
      reader.onload = function(e) {
        var data = e.target.result
        var wb = XLSX.read(data, { type: 'binary' })
        var result = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
        _this.getList(result)
      }
      reader.readAsBinaryString(file)
    },
    getList(result) {
      // excel数据再处理
      result.forEach((element, index, list) => {
        var obj = {
          name: '',
          idnumber: '',
          direction: '',
          jobrank: '',
          unit: ''
        }
        for (var key in this.prop) {
          obj[key] = element[this.prop[key]]
        }
        this.tableData.push(obj)
      })
    },
    comfirmUpload() {
      let _this = this
      let data = {
        tableData: this.tableData,
        project_id: this.$route.params.id,
        type: 3
      }
      let errorData = []
      data.tableData.forEach((element, index) => {
        element['index'] = index
      })
      this.apiPost('admin/Report/ExpertImport', data).then(res => {
        this.handelResponse(res, data => {
          if (res.data.isSuccess) {
            // 全部上传成功
            _g.toastMsg('success', '全部上传成功')
            _this.tableData = []
            _this.getTable()
          } else {
            // 部分上传成功，则只显示失败的上传信息，并将失败的原因填写到表格
            _this.showError = true
            if (data.errorList.length != _this.tableData.length) {
              _this.getTable()
            }
            data.errorList.forEach((errorEl) => {
              _this.tableData[errorEl.index]['error'] = errorEl.msg
              errorData.push(_this.tableData[errorEl.index])
            })
            /* data.errorList.forEach((errorEl, errIndex) => {
              _this.tableData.forEach((tableEl, tableIndex) => {
                if (errorEl.index === tableEl.index) {
                  console.log(errorEl, errIndex) // 后台反的错误信息
                  console.log(tableEl, tableIndex) // 传的具体信息
                  tableEl['error'] = errorEl['msg']
                  errorData.push(tableEl)
                }
              })
            }) */
            _this.tableData = errorData
          }
        })
      })
    },
    addClass({ row, column, rowIndex, columnIndex }) {
      if (column.property == 'error') {
        return { padding: '6px 0', color: 'red' }
      } else {
        return { padding: '6px 0' }
      }
    },
    exportError() {
      var that = this
      require.ensure([], () => {
        const {
          export_json_to_excel
        } = require('../../../../vendor/export2Excel')
        const tHeader = [
          '专家姓名',
          '身份证号',
          '研究方向',
          '职称',
          '所在单位',
          '失败原因'
        ]
        const filterVal = [
          'name',
          'idnumber',
          'direction',
          'jobrank',
          'unit',
          'error'
        ] // 导出的表头字段名，其实就是对应table的prop名字
        const list = that.tableData
        const data = that.formatJson(filterVal, list)
        export_json_to_excel(tHeader, data, '专家导入失败原因表') // 导出的表格名称，根据需要自己命名
      })
    },
    Delete(row) {
      // 点击的第几个delete按钮（row.$index）,就删除this.tableData中的数组
      this.tableData.forEach((element, index) => {
        if (index === row.$index) {
          this.tableData.splice(row.$index, 1)
          if (this.tableData.length === 0) {
            this.showError = false
          }
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    downExpert() {
      var that = this
      require.ensure([], () => {
        const {
          export_json_to_excel
        } = require('../../../../excel2/export2Excel')
        const tHeader = [
          'id',
          '专家姓名',
          '身份证号',
          '研究方向',
          '职称',
          '所在单位',
          '登陆账号',
          '登陆密码'
        ]
        const filterVal = [
          'id',
          'name',
          'idnumber',
          'direction',
          'jobrank',
          'unit',
          'username',
          'password'
        ] // 导出的表头字段名，其实就是对应table的prop名字
        const list = that.multipleSelection
        const data = that.formatJson(filterVal, list)
        export_json_to_excel(tHeader, data, '结题专家信息表') // 导出的表格名称，根据需要自己命名
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.getTable()
    },
    getTable() {
      this.loading = true
      let data = {
        page: this.currentPage,
        project_id: this.$route.params.id,
        level: 5
      }
      this.apiPost('admin/Report/ExpertList', data).then(res => {
        this.handelResponse(res, data => {
          this.detailData = res.data.data
          this.total = Math.ceil(data.total / data.per_page)
        })
        this.loading = false
      })
    }
  },
  created() {
    _g.closeGlobalLoading()
    this.getTable()
  },
  mixins: [http]
}
</script>
<style scoped>
.box {
  position: relative;
  border-radius: 3px;
  background: #fff;
  border-top: 3px solid #d2d6de;
  margin-bottom: 20px;
  width: 100%;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
  border-top-color: #3c8dbc;
}
.box-header {
  height: 34px;
  line-height: 34px;
  color: #444;
  display: block;
  padding: 10px;
  position: relative;
}
.box-title {
  font-weight: 700;
  letter-spacing: 3px;
  display: inline-block;
  font-size: 18px;
  margin: 0;
}
.box-body {
  border-top-left-radius: 0;
  border-top-right-radius: 0;
  border-bottom-right-radius: 3px;
  border-bottom-left-radius: 3px;
  padding: 10px;
  min-height: 0.01%;
  overflow-x: auto;
}
</style>
